<?php

/*
	info: 优惠劵列表页
	date: 2011-12-18
*/

define('USER_LOGIN_CHECK', TRUE);
define('PAGESCRIPT', 'coupon');
require dirname(__FILE__).'/include/common.inc.php';

$newsCategoryDataModel = CategoryDataModel::factory('news', array('cache' => true));

$webglobal['file_coupon'] = array();

if ($webglobal['action'] == 'view') {
	$webrequest['id'] = isset($webrequest['id']) && $webrequest['id'] ? intval($webrequest['id']) : 0;
	if (!$webrequest['id']) {
		global_ShowMessage('对不起,系统中没有该优惠劵', '', 'BACK');
	}
	
	$webglobal['file_coupon']['couponData'] = cache_GetCouponDetail($webrequest['id']);

	if (!$webglobal['file_coupon']['couponData']['coupon'] || !isset($webglobal['file_coupon']['couponData']['company']) || !$webglobal['file_coupon']['couponData']['company']) {
		global_ShowMessage('对不起,没有该优惠劵信息!', '', 'BACK');
	}

	if ($webglobal['file_coupon']['couponData']['coupon']['status'] != 1) {
		if ($webglobal['file_coupon']['couponData']['coupon']['status'] == 0) {
			global_ShowMessage('对不起 该优惠劵正在审核，请稍后!');
		} elseif ($webglobal['file_coupon']['couponData']['coupon']['status'] == 2) {
			global_ShowMessage('对不起 该优惠劵没有通过审核!');
		} else {
			global_ShowMessage('对不起,没有该优惠劵信息!');
		}
		
	}

	global_ConnectDB();
	//查看商家签到列表
	$companyCommentFiles = array('`tm_user`.`nickname` as personname', '`tm_user`.`avatar` as avatar', '`tm_company`.`name` as companyname', '`tm_company_comment`.id','`tm_company_comment`.`photo`', '`tm_company_comment`.title','`tm_company_comment`.`content`', '`tm_company_comment`.inquiry_title','`tm_company_comment`.inquiry_result', '`tm_company_comment`.`floor`','`tm_company_comment`.ref_id', '`tm_company_comment`.`score`','`tm_company_comment`.`addtime`', '`tm_company_comment`.`status`','`tm_company_comment`.user_type'
	);
	$webglobal['file_coupon']['checkin'] = array();
	$fileSql = implode(',', $companyCommentFiles);

	$tempsearchsql = ' WHERE `tm_company_comment`.company_id = '. $webglobal['file_coupon']['couponData']['coupon']['company_id'] .' AND `tm_company_comment`.`status` = 1';

	$webrequest['page'] = isset($webrequest['page']) ? max(1, intval($webrequest['page'])) : 1;
	$webglobal['file_coupon']['perpage'] = 10;
	$webglobal['file_coupon']['datanum'] = $db->GetNum("SELECT COUNT(*) FROM {$webconfig['dbpre']}company_comment LEFT JOIN `tm_company` ON `tm_company_comment`.`company_id` = `tm_company`.`id`{$tempsearchsql}");

	if ($webglobal['file_coupon']['datanum'] > 0) {
		$option = array(
			'page' => '@@'
		);

		$webglobal['page'] = global_Page($webglobal['file_coupon']['datanum'], $webglobal['file_coupon']['perpage'], $webrequest['page'], buildURLForModule('checkin', $option));
		$tempstartnum = ($webrequest['page']-1)*$webglobal['file_coupon']['perpage'];

		$query = $db->Query("SELECT {$fileSql} FROM `tm_company_comment` LEFT JOIN `tm_company` ON `tm_company_comment`.`company_id` = `tm_company`.`id` LEFT JOIN `tm_user` ON `tm_company_comment`.`user_id` = `tm_user`.`id`{$tempsearchsql} ORDER BY `tm_company_comment`.addtime DESC LIMIT $tempstartnum, {$webglobal['file_coupon']['perpage']}");
		while ($tempdata = $db->FetchArray($query)) {
			$tempdata['content'] = preg_replace("/\{:(.*?):\}/ies", "replaceImage('\\1')", $tempdata['content']);
			$tempdata['addtime'] =  !empty($tempdata['addtime']) ? global_FormatTime($tempdata['addtime']) : '';
			$webglobal['file_coupon']['checkin'][$tempdata['id']] = $tempdata;
		}
	}

	//统计优惠劵的浏览次数
	$currentTime = global_FormatTime($webserver['timestamp'], 'FD');
	list($year, $month, $day) = explode('-', $currentTime);
	$tempTime = global_ConvTime($currentTime . '00:00:00');

	$viewedCouponID = array();
	$isHaveViewed = false;
	$updateID = 0;

	if (isset($webcookie['coupon']) && $webcookie['coupon'] && isset($webcookie['viewtime']) && $webcookie['viewtime']) {
		if ($webcookie['viewtime'] != $tempTime) {
			global_ClearCookie('coupon');
			global_ClearCookie('viewtime');
		} else {
			$viewedCouponID = explode(',', $webcookie['coupon']);
			if (in_array($webrequest['id'], $viewedCouponID)) {
				$isHaveViewed = true;
			}
		}
	} else {
		global_ClearCookie('coupon');
		global_ClearCookie('viewtime');
	}

	if ($isHaveViewed) {
		$db->Update('coupon_views', "views=views + 1", 'coupon_id = ' . $webrequest['id'] . ' AND addtime = ' . $tempTime);
	} else {
		if ($couponView = $db->GetOne("SELECT id FROM {$webconfig['dbpre']}coupon_views WHERE coupon_id = {$webrequest['id']} AND year = {$year} AND month = {$month} AND day = {$day}")) {
			$db->Update('coupon_views', "views=views + 1", 'id='.$couponView['id']);
		} else {
			$insertData = array(
				'coupon_id' => $webrequest['id'],
				'year'      => $year,
				'month'     => $month,
				'day'       => $day,
				'week'      => global_FormatTime($webserver['timestamp'], 'N'),
				'weeknum'   => global_FormatTime($webserver['timestamp'], 'W'),
				'quarter'   => ceil($month / 3),
				'views'     => 1,
				'addtime'   => $tempTime,
			);
			$db->Insert('coupon_views', $insertData, TRUE);
		}
		$viewedCouponID[] = $webrequest['id'];
	}

	global_SetCookie('viewtime', $tempTime);
	global_SetCookie('coupon', implode(',', $viewedCouponID));

} elseif ($webglobal['action'] == 'favorite') {
	
	if ($user['base_uid']<=0) {
		global_ShowMessage("对不起，您还没有登录。", WEBURLPATH.'/login.php');
	}
	if ($user['base_type']!=0) {
		global_ShowMessage("对不起，商家不允许收藏优惠劵。", '', 'BACK');
	}

	$webrequest['id'] = isset($webrequest['id']) && $webrequest['id'] ? intval($webrequest['id']) : 0;
	if (!$webrequest['id']) {
		global_ShowMessage('对不起,没有可收藏的优惠劵', '', 'BACK');
	}
	if (!$webglobal['file_coupon']['couponData'] = cache_GetCouponDetail($webrequest['id'])) {
		global_ShowMessage('对不起,系统中没有该优惠劵信息', '', 'BACK');
	}
	//查询用户是否已经收藏过该优惠劵
	if ($favoriteData = $db->GetOne("SELECT id FROM {$webconfig['dbpre']}coupon_favorites WHERE coupon_id = " . $webrequest['id'] . ' AND user_id = '. $user['base_uid'])) {
		global_ShowMessage('对不起，您已经收藏过该优惠劵。', '', 'BACK');
	} else {
		$insertData = array(
			'coupon_id' => $webrequest['id'],
			'user_id'      => $user['base_uid'],
			'addtime'     => $webserver['timestamp']
		);
		$db->Insert('coupon_favorites', $insertData, TRUE);
		//更新优惠劵收藏次数
		$db->Update('coupon', "favorites_num=favorites_num+1", "id = ".$webrequest['id']);
		
		global_ShowMessage('恭喜您，优惠劵收藏成功', WEBURLPATH . '/coupon.php?action=view&id='.$webrequest['id']);
	}
} else {
	//获取参数
	$webrequest['page'] = isset($webrequest['page']) ? max(1, intval($webrequest['page'])) : 1;

	$webrequest['c'] = isset($webrequest['c']) && $webrequest['c'] ? intval($webrequest['c']) : 0; //优惠劵分类ID
	$webrequest['a'] = isset($webrequest['a']) && $webrequest['a'] ? intval($webrequest['a']) : 0; //商圈ID
	$webrequest['s'] = isset($webrequest['s']) && $webrequest['s'] ? trim($webrequest['s']) : ''; //搜索条件
	$webrequest['l'] = isset($webrequest['l']) && $webrequest['l'] ? intval($webrequest['l']) : 10; //显示条数

	$options = array();
	foreach (array('c', 'a', 's', 'l') as $field) {
		if (isset($webrequest[$field]) && $webrequest[$field]) {
			$options[$field] = $webrequest[$field];
		}
	}

	$webglobal['file_coupon']['urlParams'] = $options;

	$webglobal['file_coupon']['pageLimit'] = array();
	//按显示个数链接
	foreach (array(10, 20, 30) as $tempLimit) {
		$curoptions = $options;
		$curoptions['l'] = $tempLimit;
		$checked = false;

		if ($webrequest['l'] && $webrequest['l'] == $tempLimit) {
			$checked = true;
		}
		$webglobal['file_coupon']['pageLimit'][] = array(
			'title'   => $tempLimit,
			'url'     => buildURLForModule('coupon.php', $curoptions),
			'checked' => $checked
		);
	}

	//获取城市商圈
	$webglobal['file_coupon']['areadata'] = array();
	if (isset($webglobal['curcityid']) && $webglobal['curcityid']) {
		if ($areadata = $areaDataModel->getChildForLayer($webglobal['curcityid'], 2, false)) {
			foreach ($areadata as $key => $value) {
				$curoptions = $options;
				$curoptions['a'] = $value['id'];
				$value['url'] = buildURLForModule('coupon.php', $curoptions);
				if (isset($webglobal['file_coupon']['areadata'][$value['upid']])) {
					$webglobal['file_coupon']['areadata'][$value['upid']]['second'][$value['id']] = $value;
				} else {
					$webglobal['file_coupon']['areadata'][$value['id']] = $value;
					$webglobal['file_coupon']['areadata'][$value['id']]['second'] = array();
				}
			}
		}
	}

	//获取所选择的商圈
	$webglobal['file_coupon']['selectarea'] = array();
	if ($webrequest['a']) {
		$webglobal['file_coupon']['selectarea'][] = $webrequest['a'];
		if ($selectArea = $areaDataModel->getItem($webrequest['a'])) {
			$webglobal['file_coupon']['selectarea'] = array_merge($webglobal['file_coupon']['selectarea'], $selectArea['upCategoryID']);
		}
	}

	//全部分类链接地址
	$curoptions = $options;
	unset($curoptions['a']);
	$webglobal['file_coupon']['allAreaUrl'] = buildURLForModule('coupon.php', $curoptions);

	//全部分类链接地址
	$curoptions = $options;
	unset($curoptions['c']);
	$webglobal['file_coupon']['allCategoryUrl'] = buildURLForModule('coupon.php', $curoptions);

	
	//获取优惠劵分类 //$webglobal['couponCategory']
	foreach ($webglobal['couponCategory'] as $key => $value) {
		$curoptions = $options;
		$curoptions['c'] = $value['id'];
		$value['url'] = buildURLForModule('coupon.php', $curoptions);
		if (isset($webglobal['couponCategory'][$value['upid']])) {
			$webglobal['couponCategory'][$value['upid']]['second'][$value['id']] = $value;
			unset($webglobal['couponCategory'][$value['id']]);
		} else {
			$webglobal['couponCategory'][$value['id']] = $value;
			$webglobal['couponCategory'][$value['id']]['second'] = array();
		}
	}

	//获取所选择的分类
	$webglobal['file_coupon']['selectcategory'] = array();
	if ($webrequest['c']) {
		$webglobal['file_coupon']['selectcategory'][] = $webrequest['c'];
		if ($selectCategory = $couponCategoryDataModel->getItem($webrequest['c'])) {
			$webglobal['file_coupon']['selectcategory'] = array_merge($webglobal['file_coupon']['selectcategory'], $selectCategory['upCategoryID']);
		}
	}

	//组合查询条件
	$endTime = $webserver['timestamp'] - 259200;
	$tempsearchsql = array('c.status = 1', 'c.endtime >= '.$endTime, 'p.status = 1');
	if (isset($webglobal['curcityid']) && $webglobal['curcityid'] && !$webrequest['a']) {
		$tempsearchsql[] = "p.city = " . $webglobal['curcityid'];
	}

	if ($webrequest['c']) {
		if ($subCategory = $couponCategoryDataModel->getChildForLayer($webrequest['c'], 0)) {
			$categoryID = array_keys($subCategory);
			$tempsearchsql[] = "c.coupon_category_id IN (" .implode(',', $categoryID). ")";
		}
	}
	if ($webrequest['a']) {
		if ($subArea = $areaDataModel->getChildForLayer($webrequest['a'], 0)) {
			$areaID = array_keys($subArea);
			$tempsearchsql[] = "p.area_id IN (" .implode(',', $areaID). ")";
		}
	}

	if ($webrequest['s']) {
		$tempsearchsql[] = $db->BuildSearchSql($webrequest['s'], array('c.name','c.introduction', 'p.name', 'p.address'));
	}

	$tempsearchsql = empty($tempsearchsql) ? '' : ' WHERE '.implode(' AND ', $tempsearchsql);

	$webglobal['file_coupon']['perpage'] = $webrequest['l'];
	$webglobal['file_coupon']['datanum'] = $db->GetNum("SELECT COUNT(*) FROM {$webconfig['dbpre']}coupon c LEFT JOIN {$webconfig['dbpre']}company p ON c.company_id = p.id{$tempsearchsql}");

	if ($webglobal['file_coupon']['datanum'] > 0) {
		$curoptions = $options;
		$curoptions['page'] = '@@';
		$webglobal['page'] = global_Page($webglobal['file_coupon']['datanum'], $webglobal['file_coupon']['perpage'], $webrequest['page'], buildURLForModule('coupon.php', $curoptions));

		$tempstartnum = ($webrequest['page']-1)*$webglobal['file_coupon']['perpage'];
		$temporderstr = "pubtime DESC";

		$query = $db->Query("SELECT c.* FROM {$webconfig['dbpre']}coupon c LEFT JOIN {$webconfig['dbpre']}company p ON c.company_id = p.id{$tempsearchsql} ORDER BY {$temporderstr} LIMIT $tempstartnum, {$webglobal['file_coupon']['perpage']}");
		$temptr = 1;
		$webglobal['file_coupon']['dataarray'] = array();

		while ($tempdata = $db->FetchArray($query)) {
			$tempdata['starttime_show'] = !empty($tempdata['starttime']) ? global_FormatTime($tempdata['starttime'], 'Y年n月j日') : '';
			$tempdata['endtime_show'] = !empty($tempdata['endtime']) ? global_FormatTime($tempdata['endtime'], 'Y年n月j日') : '';
			$tempdata['pubtime_show'] = !empty($tempdata['pubtime']) ? global_FormatTime($tempdata['pubtime']) : '';

			if ($tempdata['image']) {
				$tempdata['thumbnail'] = array(
					'big' => getThumbnails($tempdata['image'], 'big'),
					'small' => getThumbnails($tempdata['image'], 'small'),
					'middle' => getThumbnails($tempdata['image'], 'middle')
				);
			}

			$webglobal['file_coupon']['dataarray'][$tempdata['id']] = $tempdata;
		}
	}

	//获取热门优惠劵
	cache_GetHotCoupon(); //$webcache['hotcoupon'](按日,周,月分组)
	//获取热点信息
	$hotnews = array(
		'row' => 8,
		'titlelen' => 30,
		'typeid' => 2,
		'listtype'=> 'commend.'
	);
	$webglobal['file_coupon']['hotnews'] = getArcList($hotnews);
	//获取热点信息
	//$newsCategoryDataModel = CategoryDataModel::factory('news', array('cache' => true));
	cache_GetHotNews($newsCategoryDataModel); //$webcache['hotnews']
}

function replaceImage($imageTitle) {
	if ($imageTitle != '') {
		return '<img src="'. WEBURLPATH . '/images/emoji/' . $imageTitle . '.png' .'" />';
	}
	return $imageTitle;
}

template_Display('coupon');
